package pl.testowka.selenium;

import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.*;

public class iterationThroughMenu {
	private WebDriver driver;
	private String baseUrl = "http://code.google.com";
	private StringBuffer verificationErrors = new StringBuffer();

	
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		// driver = new HtmlUnitDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	
	public void testSeleniumMeni() {
		List<WebElement> meni = driver.findElements(By
				.xpath("//html/body/div[2]/a"));
		List<String> urls = new LinkedList<String>();

		for (WebElement webElement : meni) {
			urls.add(webElement.getAttribute("href").toString());
		}
		for (String url : urls) {
			driver.get(url);
		}
	}

	
	public void shouldVerifyMenuClickable() throws Exception {
		int elementId = 1;
		while (isElementPresent(By.xpath("//html/body/div[2]/a[" + elementId
				+ "]"))) {
			click(By.xpath("//html/body/div[2]/a[" + elementId + "]"));
			elementId++;
		}
	}
	//test
	
	
	public void testIterateMenu() {
		driver.get("http://code.google.com/p/selenium/");
		iterateMenu("//html/body/div[2]/a");
	}
	
	public void iterateMenu(String path) {
		List<WebElement> menu = driver.findElements(By.xpath(path));
		Object[] list = menu.toArray();
		for (int i = 1; i <= list.length; i++) {
			click(By.xpath(path+"["+i+"]"));
			}
	}

	private void click(By identifier) {
		driver.findElement(identifier).click();
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
